<template>
  <div class="app-container-form" :class="$style.wrapper">
    <!-- 基础表单信息 -->
    <el-card header="基础信息" style="width: 100%">
      <div slot="header" class="clearfix">
        <span>基础信息</span>
      </div>
      <div>
        <el-row>
          <el-col :span="24">
            <el-form
              ref="formMain"
              :model="form"
              :rules="tableData.rules"
              status-icon
              label-width="120px"
              ><el-row>
                <el-col
                  v-for="(field, idx) in _fields"
                  :span="field.span || 8"
                  :key="idx"
                >
                  <el-form-item
                    :key="idx"
                    :label="field.label"
                    :prop="field.prop"
                  >
                    <slot
                      v-bind="{ data: form, field, child: tableDataChild }"
                      :name="'form-' + field.prop"
                    >
                      <el-input
                        v-model="form[field.prop]"
                        :placeholder="'请输入' + field.label"
                        :disabled="field.disabled"
                      />
                    </slot>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
        </el-row>

        <el-row v-if="_columnsChild.length > 0">
          <el-col :span="24">
            <!-- 子表信息 -->
            <slot name="childTable">
              <div style="position: relative">
                <div :class="$style.childsearch">
                  <slot
                    name="childsearch"
                    v-bind="{ tableData, tableDataChild }"
                  >
                    <el-input
                      placeholder="请输入关键字查询"
                      prefix-icon="el-icon-search"
                      size="small"
                      v-model="serachFuzzy"
                    ></el-input>
                    <div>
                      <slot
                        name="childTableToolbar"
                        v-bind="{ tableData, tableDataChild }"
                      >
                        <el-button
                          type="primary"
                          icon="el-icon-plus"
                          size="mini"
                          @click="handleAddChild"
                          v-hasPermi="[modulePermi + ':add']"
                        >
                          新增明细
                        </el-button>
                      </slot>
                    </div>
                  </slot>
                </div>

                <el-tabs v-model="activeName">
                  <el-tab-pane label="明细数据" name="first">
                    <ux-grid
                      ref="plxTable"
                      :data="tableDataChild.rows"
                      :validConfig="{ autoPos: true }"
                      :height="tableDataChild.height"
                      :rules="rules"
                      show-header-overflow="ellipsis"
                      :edit-config="{ trigger: 'click', mode: 'cell' }"
                    >
                      <ux-table-column
                        v-for="item in _columnsChild"
                        :key="item.prop"
                        :type="item.type"
                        :align="item.align"
                        :resizable="item.resizable"
                        :field="item.prop"
                        :title="item.label"
                        :formatter="item.formatter"
                        :sortable="item.sortable"
                        :width="item.width"
                        :min-width="item.minWidth"
                        :fixed="item.fixed"
                        :edit-render="item.edit"
                        show-overflow="title"
                      >
                        <template
                          v-slot:edit="scope"
                          v-if="
                            !item.formatter &&
                            item.type !== 'index' &&
                            item.type !== 'selection'
                          "
                        >
                          <slot
                            v-bind="{
                              data: scope.row,
                              field: item,
                              scope: scope,
                            }"
                            :name="'formChild-' + item.prop"
                          >
                            <el-input v-model="scope.row[item.prop]"></el-input>
                          </slot>
                        </template>
                        <template
                          v-slot="scope"
                          v-if="
                            !item.formatter &&
                            item.type !== 'index' &&
                            item.type !== 'selection'
                          "
                        >
                          <slot
                            v-bind="{
                              data: scope.row,
                              field: item,
                              scope: scope,
                            }"
                            :name="item.prop"
                          >
                            <span>{{ scope.row[item.prop] }}</span>
                          </slot>
                        </template>
                      </ux-table-column>
                      <ux-table-column
                        title="操作"
                        width="80"
                        fixed="right"
                        :show-overflow-tooltip="true"
                        align="center"
                      >
                        <template #default="scope">
                          <slot name="operationChild" v-bind="scope">
                            <el-button
                              type="text"
                              size="small"
                              icon="el-icon-delete"
                              @click="
                                handleDeleteChild(scope.row, scope.rowIndex)
                              "
                              v-hasPermi="[modulePermi + ':remove']"
                            >
                              删除
                            </el-button>
                          </slot>
                        </template>
                      </ux-table-column>
                    </ux-grid>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </slot>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <div class="dialog-footer" style="margin-top: 10px">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import BaseService from "@/api/base/base";
export default {
  props: {
    id: {
      type: [String, Number],
      default: "",
    },
    value: {
      type: Object,
      default: () => {},
    },
    childList: {
      type: Array,
      default: () => [],
    },
    rules: {
      type: Object,
      default: () => {},
    },
  },
  inject: ["hdTable"],
  data() {
    return {
      modulePermi: this.hdTable.modulePermi,
      baseService: new BaseService(this.hdTable.modulePath),
      activeName: "first",
      solution: {},
      solutions: [],
      readOnly: false,
      form: { childList: [] },
      rulesChild: {},
      serachFuzzy: "",
      tableData: {
        title: "",
        height: 0, //document.body.clientHeight - 200,
        rows: [],
        loading: false,
        total: 0,
        selection: [],
        title: "",
        open: false,
        form: {
          createBy: undefined,
          createTime: undefined,
          version: undefined,
          state: undefined,
        },
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          state: null,
          createBy: null,
          // params: {
          //   beginDate: this.$moment().startOf('month').format(),
          //   endDate: this.$moment().endOf('month').format(),
          // },
        },
        rules: {},
      },
      tableDataChild: {
        height: 400,
        rows: [],
        loading: false,
        total: 0,
        open: false,
        form: {},
        selection: [],
        rules: {},
        queryParams: {
          pageNum: 1,
          pageSize: 9999,
        },
      },
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          this.init(val);
        }
      },
    },
  },
  created() {
    if (this.value) {
      this.init(this.value);
    } else {
      if (this.id) {
        this.baseService.getDetail(this.id).then((response) => {
          this.edit = true;
          if (response) {
            this.form = response.data;
            this.getListChild(this.form);
          }
        });
      }
    }
  },
  computed: {
    _fields() {
      let tmpArr = this.hdTable.columns.filter(
        (a) => !a.type && !(a.isField === false)
      );
      if (this.hdTable.tableData.title === "修改") {
        tmpArr = tmpArr.map((o) => {
          let a = { ...o };
          if (a.disabledEdit === true) {
            a.disabled = true;
          }
          return a;
        });
      }
      return tmpArr;
    },
    _columnsChild() {
      return this.hdTable.columnsChild
        .filter((a) => !(a.isForm === false))
        .map((a) => {
          if (["selection", "index"].includes(a.type)) {
            if (!a.align) a.align = "center";
            if (!a.label) a.label = "#";
          }
          return a;
        });
    },
    filterFuzzy() {
      let searchData = this.tableDataChild.rows;
      this.serachFuzzy = this.serachFuzzy.trim();
      if (this.serachFuzzy) {
        searchData = searchData.filter((o) => {
          return JSON.stringify(o).indexOf(this.serachFuzzy) !== -1;
        });
      }
      return searchData;
    },
  },
  methods: {
    init(val) {
      const form = Object.assign({}, val);
      this._fields.forEach((o) => {
        if (!form[o.prop]) form[o.prop] = undefined;
      });
      this.form = form;
      this.tableData.form = this.form;
      this.tableData.rules = this.hdTable.tableData.rules;
      if (this.form.id) {
        this.getListChild(this.form);
      } else {
        this.tableDataChild.rows = [];
      }
    },
    getListChild(row) {
      if (row && row.id && this.hdTable.columnsChild.length > 0) {
        this.tableDataChild.loading = true;
        const tmp = { ...row };
        delete tmp.state;
        this.baseService.getListChild(tmp).then((response) => {
          this.tableDataChild.rows = response.data;
          this.tableDataChild.loading = false;
        });
      } else {
        this.tableDataChild.rows = [];
      }
    },
    setForm(data, type) {
      Object.assign(this.form, data);
    },
    setTable(data) {
      this.tableDataChild.rows = data;
    },
    /** 提交按钮 */
    submitForm() {
      this.form.childList = this.tableDataChild.rows;
      this.form.listChild = this.tableDataChild.rows;
      this.$refs["formMain"].validate((valid) => {
        if (valid) {
          const opt = {};
          this.$emit("confirm", this.form, opt);
          if (opt.valid === false) return;
          this.baseService.add(this.form).then(() => {
            this.msgSuccess("操作成功");
            this.hdTable.tableData.open = false;
            this.hdTable.getList();
          });
        }
      });
    },
    /** 新增按钮操作 */
    handleAddChild() {
      this.$refs["formMain"].validate((valid) => {
        if (valid) {
          this.tableDataChild.title = "新增明细";
          let tmp = {
            productCode: "",
            productName: "",
            productNormModel: "",
            productNumber: "",
          };
          this.tableDataChild.rows.push(tmp);
        }
      });
    },
    handleDeleteChild(data, idx) {
      this.tableDataChild.rows.splice(idx, 1);
    },
    cancel() {
      this.hdTable.tableData.open = false;
      this.resetForm("formMain");
      this.tableDataChild.rows = [];
    },
  },
};
</script>

<style module lang="scss">
.wrapper {
  :global {
    .el-form-itemxx {
      margin-bottom: 10px;
    }
    .el-form-item__content {
      line-height: 34px;
    }
  }
  .childsearch {
    display: flex;
    padding: 5px;
    position: absolute;
    right: 0px;
    width: 400px;
    z-index: 9;
    div + div {
      padding-left: 10px;
    }
  }
}
</style>
